<template>
  <view class="page-container">
    <!-- 用户信息 -->
    <view v-if="userInfo" class="user-section">
      <image class="avatar" :src="proxy.$tool.getResources(userInfo.avatar)" mode="aspectFill"/>
      <text class="username">{{ userInfo.name }}</text>
    </view>
    <view v-else class="login-button">
      <span v-if="!loginBtnLoading" @click="auth()">点击登录</span>
      <up-loading-icon v-else textColor="#007aff" text="点击登录"></up-loading-icon>
    </view>

    <!-- 按钮 -->
    <view class="invite-button" @click="createRoom()">
      创建房间开启一局比赛
    </view>

    <!-- 加入房间 -->
    <view class="join-roome" @click="roomModel.open()">
      加入房间
    </view>

    <!-- 浮动球体 -->
    <view class="advertisement">
      <canvas v-show="bubbleEntity.show" canvas-id="bubbleCanvas" style="height: 100%;width: 100%;"></canvas>
    </view>

    <!--  加入房间  -->
    <up-modal

        :show="roomModel.show"
        :title="roomModel.title"
        :closeOnClickOverlay="true"
        @confirm="joinRoom()"
        @close="roomModel.close()">
      <view class="slot-content" style="padding: 30px;z-index: 999">
        <up-input :key="roomModel.show" :focus="roomModel.inputFocus" v-model="roomModel.number"></up-input>
      </view>
    </up-modal>

  </view>
</template>

<script setup>
import {
  computed,
  getCurrentInstance,
  ref
} from "vue";
import {
  useStore
} from "vuex";
import {onShow} from "@dcloudio/uni-app"; // 正确导入 onLoad

const {
  proxy
} = getCurrentInstance();
const store = useStore();
const userInfo = computed(() => store.state.userInfo);

//气泡相关内容

const bubbleEntity = ref({
  /**
   * 是否显示气泡
   */
  show:true,

  //气泡json
  bubbles: [
    {"text": "十八罗汉"},
    {"text": "杠上花"},
    {"text": "清一色"},
    {"text": "碰碰胡"},
    {"text": "平胡"},
    {"text": "混一色"},
    {"text": "七对"},
    {"text": "十三幺"},
    {"text": "大三元"},
    {"text": "小三元"},
    {"text": "大四喜"},
    {"text": "小四喜"},
    {"text": "自摸"},
    {"text": "抢杠胡"},
    {"text": "海底捞月"},
    {"text": "双竖杠"},
    {"text": "一条龙"},
    {"text": "混一色"},
    {"text": "对对胡"},
    {"text": "四暗刻"},
    {"text": "三暗刻"},
    {"text": "清龙"},
    {"text": "大四喜"},
    {"text": "国士无双"},
    {"text": "大明杠"},
    {"text": "小明杠"},
    {"text": "大单吊"},
    {"text": "流局"},
    {"text": "缺一色"},
    {"text": "碰牌"},
    {"text": "天胡"},
    {"text": "相公"},
    {"text": "将对"},
    {"text": "杠上炮"},
    {"text": "龙七对"},
    {"text": "天胡"},
    {"text": "地胡"},
    {"text": "断幺九"},
    {"text": "过胡"},
    {"text": "加翻"},
    {"text": "双龙会"},
    {"text": "恭喜发财"},
    {"text": "身体健康"},
  ],

  /**
   * 绘制所有气泡
   */
  drawBubbles: () => {
    const context = uni.createCanvasContext('bubbleCanvas');
    // 获取父容器的尺寸
    const query = uni.createSelectorQuery();
    query.select('.advertisement').boundingClientRect(res => {
      const canvasWidth = res.width;
      const canvasHeight = res.height;
      const bubbleMargin = 10; // 气泡之间的最小间距
      // 清空画布
      context.clearRect(0, 0, canvasWidth, canvasHeight);

      // 计算气泡的位置
      let attempts = 0;
      const maxAttempts = 1000; // 最大尝试次数避免死循环
      const positions = [];

      // 为每个气泡生成位置并确保气泡不重叠
      bubbleEntity.value.bubbles.forEach(bubble => {
        let x, y, overlap;
        do {
          // 尝试随机位置
          x = Math.max(bubble.size, Math.random() * (canvasWidth - (bubble.size / 2) - bubbleMargin * 2) + bubbleMargin);
          y = Math.max(bubble.size, Math.random() * (canvasHeight - (bubble.size / 2) - bubbleMargin * 2) + bubbleMargin);

          // 检查气泡是否重叠
          overlap = positions.some(pos => {
            const dist = Math.sqrt(Math.pow(pos.x - x, 2) + Math.pow(pos.y - y, 2));
            return dist < (bubble.size / 2 + pos.size / 2);
          });

          attempts++;
          if (attempts > maxAttempts) {
            break; // 防止无限循环
          }
        } while (overlap);

        positions.push({x, y, size: bubble.size});

        bubbleEntity.value.drawBubble(context, x, y, bubble);
      });

      context.draw();
    }).exec();
  },

  /**
   * 回执单个气泡
   */
  drawBubble: (context, x, y, bubble) => {
    const radius = bubble.size / 2;
    // 使用线性渐变
    const gradient = context.createLinearGradient(x - radius, y - radius, x + radius, y + radius);
    gradient.addColorStop(0, '#00BFFF'); // 从浅蓝色开始
    gradient.addColorStop(1, '#1E90FF'); // 到深蓝色
    context.setFillStyle(gradient); // 设置渐变色填充
    // 绘制圆形气泡
    context.beginPath();
    context.arc(x, y, radius, 0, 2 * Math.PI);
    context.fill();
    // 绘制文字
    context.setFontSize(13);
    context.setFillStyle('#FFFFFF'); // 文字颜色
    context.setTextAlign('center');
    context.setTextBaseline('middle');
    context.fillText(bubble.text, x, y);
  }
})


onShow(() => {
  // 动态调整气泡大小，根据文字长度
  bubbleEntity.value.bubbles.forEach(bubble => {
    const textLength = bubble.text.length;
    bubble.size = Math.max(40, textLength * 15); // 文字长度决定气泡大小，最小40
  });
  bubbleEntity.value.drawBubbles();
})


const roomModel = ref({
  show: false,
  title: "请输入房间号",
  //房间号
  number: "",
  //输入框聚焦
  inputFocus: false,
  /**
   * 打开弹框
   */
  open: () => {
    if (userInfo.value == null) {
      uni.$u.toast("请登录")
      return;
    }
    //关闭气泡
    bubbleEntity.value.show=false;

    //重置数据
    roomModel.value.number = "";

    roomModel.value.show = true
    setTimeout(() => {
      roomModel.value.inputFocus = true
    }, 100)
  },
  close: () => {
    roomModel.value.inputFocus = false
    //打开气泡
    bubbleEntity.value.show=true;
    setTimeout(() => {
      roomModel.value.show = false
    }, 100)
  }
})

//创建并加入房间
const createRoom = () => {
  //判断是否登录
  if (userInfo.value == null) {
    uni.$u.toast("请登录")
  } else {
    //判断是否存在未开始的房间
    proxy.$request.get('/bus-room/findNoStartRoomByUser').then(res => {
      //判断是否存在未开始的房间
      if (res == null) {
        //不存在直接进入创建房间的页面
        uni.navigateTo({
          url: '/pages/joinRoom/joinRoom'
        })
      } else {
        //存在房间
        uni.navigateTo({
          url: `/pages/joinRoom/joinRoom?id=${res.roomId}`
        })
      }
    })
  }
}


/**
 * 加入房间
 */
const joinRoom = () => {
  if (userInfo.value == null) {
    uni.$u.toast("请登录")
    return;
  }
  //判断是否输入了内容
  if (roomModel.value.number == null || roomModel.value.number === "") {
    uni.$u.toast("请输入房间号")
    return;
  }
  proxy.$request.get(`/bus-room/joinRoom/${roomModel.value.number}`).then(res => {
    roomModel.value.show = false
    //加入成功切换到房间页面去
    uni.navigateTo({
      url: `/pages/joinRoom/joinRoom?id=${roomModel.value.number}`
    })
  })
}

//登录按钮loding防止多次请求
const loginBtnLoading = ref(false);

/**
 * 认证
 */
const auth = function () {
  loginBtnLoading.value = true;
  proxy.$tool.login(() => {
    loginBtnLoading.value = false;
  }, () => {
    loginBtnLoading.value = false;
  })
}

</script>
<style lang="less" scoped>
.page-container {
  display: flex;
  height: 100vh; /* 设置为100%视口高度 */
  flex-direction: column;
  align-items: center;
  padding: 0 16px;
  background-color: #f5f5f5;
  justify-content: space-between; /* 分配空间，确保广告区域占用剩余空间 */

  .user-section {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30px;
    height: 120px;
    width: 120px;

    .avatar {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      margin-bottom: 8px;
    }

    .username {
      font-size: 16px;
      color: #888;
    }
  }

  .login-button {
    margin-bottom: 150px;
    margin-top: 10px;
    padding: 6px 12px;
    font-size: 14px;
    color: #007aff;
    border: 1px solid #007aff;
    border-radius: 4px;
    background-color: #fff;
    text-align: center;
  }

  .invite-button {
    background-color: #1aad19;
    color: #fff;
    font-size: 16px;
    padding: 12px 24px;
    border-radius: 8px;
    text-align: center;
    margin-bottom: 16px;
    height: 20px;
  }

  .join-roome {
    font-size: 14px;
    color: #007aff;
    margin-bottom: 16px;
    text-align: center;
    height: 50px;
  }

  .advertisement {
    width: 100%;
    height: calc(100% - 300px);
    z-index: 1;
  }
}


/* 为 up-modal 设置更高的 z-index */
:deep(.u-popup__content) {
  z-index: 9999; /* 设置较高的 z-index */
  position: fixed; /* 固定在屏幕上的位置 */
}


</style>